<script setup lang="ts">
import type { CheckAppointmentNumberDO } from '@/api/check-appointment-number';
import dayjs from 'dayjs';
import { computed, ref } from 'vue';
import { CheckAppointmentNumberApi } from '@/api/check-appointment-number';
import AuthBar from '@/components/authBar/index.vue';
import { getStatus } from '@/enums/exam.enums';
import { useRequest } from '@/hooks/useRequest';
import { useScrollViewHelper } from '@/hooks/useScrollVIewHelper';
import { checkTimeAvailable } from '@/utils/date.utils';
import { currRoute, withQueryString } from '@/utils/router.utils';

const {
  $scrollContainer,
  $scrollCard,
  onScroll,
  scrollToIndex,
  handleScroll,
  percentage,
  scrollLeft,
  scrollAnimation,
  canLeftScroll,
  canRightScroll
} = useScrollViewHelper();

// 日期列表
const dateList = Array.from({ length: 15 }).fill(dayjs()).map((today: dayjs.Dayjs, index) => {
  return today.add(index, 'day');
});

const selectedDate = ref(dayjs());

async function handleSelectDate(date: dayjs.Dayjs) {
  selectedDate.value = date;
  // 卡片位置
  const index = dateList.indexOf(date);
  scrollToIndex(index);
  getCheckAppointmentNumber();
}

const {
  data: timeRangeList,
  runAsync: getCheckAppointmentNumber
} = useRequest(() => CheckAppointmentNumberApi.getCheckAppointmentNumber({
  date: selectedDate.value.format('YYYY-MM-DD')
}), {
  onBeforeRequest() {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
  },
  onComplete() {
    uni.hideLoading();
  }
});

interface TimeRangeItemProps extends CheckAppointmentNumberDO {
  available: boolean
  desc: string
  status: string
}

const formatTimeRangeList = computed(() => {
  return timeRangeList.value?.map(item => {
    const isAvailable = checkTimeAvailable(selectedDate.value, item.endTime);

    //  是否可预约 available
    const canSelect = item.remainingCount > 0 && isAvailable;

    const desc = canSelect ? `${item.remainingCount}个号可约` : !isAvailable ? '不可预约' : '已约满';

    return {
      ...item,
      available: canSelect,
      desc,
      status: getStatus(item.remainingCount, isAvailable)
    } as TimeRangeItemProps;
  });
});

const selectTime = ref<TimeRangeItemProps>();

function handleSelectTime(item: TimeRangeItemProps) {
  // 判断是否可选择
  if (!item.available) {
    return;
  }

  if (!checkTimeAvailable(selectedDate.value, item.endTime)) {
    selectTime.value = undefined;
    getCheckAppointmentNumber();
    uni.showToast({
      title: '该时间段已过期',
      icon: 'none'
    });
    return;
  }
  selectTime.value = item;
}

const { query } = currRoute();

function handleNext() {
  if (!selectTime.value) {
    uni.showToast({
      title: '请选择预约时间',
      icon: 'none'
    });
    return;
  }
  uni.navigateTo({
    url: withQueryString('/pages/examination/planPayConfirm', {
      ...query,
      appointmentDate: selectedDate.value.valueOf(),
      timePeriod: `${selectTime.value.startTime}-${selectTime.value.endTime}`,
      timePeriodId: selectTime.value.timePeriodId
    })
  });
}
</script>

<template>
  <view class="plan-appointment flex-col">
    <AuthBar />
    <view class="flex-1 overflow-auto">
      <view class="page-title mt-55">
        预约体检时间
      </view>
      <view class="page-subtitle">
        请选择您方便的体检日期和时间段
      </view>
      <view class="page-content mt-40 px-48 pb-40">
        <!-- 日期选择 -->
        <view class="date-selector pb-26 pl-41 pt-35">
          <view class="date-selector__title">
            选择日期
          </view>

          <view class="mt-16">
            <scroll-view
              class="date-card__group" :class="[$scrollContainer]" scroll-x :scroll-left="scrollLeft"
              :scroll-with-animation="scrollAnimation" :show-scrollbar="false" @scroll="onScroll"
            >
              <view
                v-for="(item, index) in dateList" :key="index" class="date-card"
                :class="[$scrollCard, { active: item.isSame(selectedDate, 'day') }]" @click="handleSelectDate(item)"
              >
                <view class="date-card__day">
                  {{ item.format("周dd") }}
                </view>
                <view class="date-card__date">
                  {{ item.date() }}
                </view>
                <view class="date-card__month">
                  {{ item.format("MM月") }}
                </view>
                <view v-if="item.isSame(dayjs(), 'day')" class="date-card__today">
                  今天
                </view>
              </view>
            </scroll-view>
            <view class="date-card__control mt-26 flex items-center px-90">
              <view class="arrow" :class="{ disabled: !canLeftScroll }" @click="handleScroll('left')">
                <i class="iconfont icon-a-duobianxing1" />
              </view>
              <view class="bar mx-20 flex-1">
                <wd-progress :percentage="percentage" hide-text :duration="0" />
              </view>
              <view class="arrow rotate-180" :class="{ disabled: !canRightScroll }" @click="handleScroll('right')">
                <i class="iconfont icon-a-duobianxing1" />
              </view>
            </view>
          </view>
        </view>

        <!-- 时间选择 -->
        <view class="time-selector mt-30 px-40 pb-50 pt-35">
          <view class="time-selector__hd flex items-center justify-between">
            <view class="time-selector__title">
              选择时间
            </view>
            <view class="time-selector__desc">
              灰色表示时段已满
            </view>
          </view>

          <view class="time-selector__content">
            <wd-row :gutter="16">
              <wd-col v-for="item in formatTimeRangeList" :key="item" :span="8">
                <view
                  class="time-selector__item mt-16"
                  :class="{ disabled: !item.available, active: item.id === selectTime?.id }"
                  @click="handleSelectTime(item)"
                >
                  <view>{{ item.startTime }} - {{ item.endTime }}</view>
                  <view class="time-selector__desc" :class="[item.status]">
                    {{ item.desc }}
                  </view>
                </view>
              </wd-col>
            </wd-row>
          </view>
        </view>

        <view class="mt-50 flex-center">
          <view class="next-btn w-708">
            <wd-button block @click="handleNext">
              下一步
            </wd-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<route type="page" lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '体检预约',
    navigationStyle: 'custom'
  }
}
</route>

<style lang="scss" scoped>
.plan-appointment {
  background-color: var(--bg-color);
  height: 100%;

  .page-title {
    font-size: 60px;
    font-weight: bold;
    color: var(--text-color);
    text-align: center;
  }

  .page-subtitle {
    text-align: center;
    font-size: 28px;
    color: var(--secondary-text-color);
    max-width: 524px;
    margin: 0 auto;
  }

  .date-selector {
    background: #e2ecfc;
    border-radius: 20px;

    .date-selector__title {
      font-size: 32px;
      font-weight: 500;
      color: var(--secondary-text-color);
    }

    .date-card__group {
      white-space: nowrap;
      overflow: auto;

      :deep(.uni-scroll-view)::-webkit-scrollbar {
        display: none;
      }

      &::-webkit-scrollbar {
        display: none;
      }

      .date-card {
        background: #fff;
        border-radius: 10px;
        position: relative;
        display: inline-block;
        margin-right: 20px;
        width: 230px;
        text-align: center;
        box-sizing: border-box;
        padding: 33px 0;

        .date-card__day {
          font-size: 32px;
          color: #4a4a4a;
        }

        .date-card__date {
          font-size: 54px;
          font-weight: 500;
          color: var(--text-color);
          margin-top: 12px;
          margin-bottom: 12px;
        }

        .date-card__month {
          font-size: 32px;
          color: var(--primary);
        }

        .date-card__today {
          position: absolute;
          font-size: 24px;
          font-weight: 500;
          top: 0;
          right: 0;
          background: #e2ecfc;
          padding: 2px 14px;
          border-radius: 100px;
          border-top-right-radius: 0;
          color: var(--primary);
          border: 1px solid #ffffff;
        }

        &.active {
          background-color: var(--primary);
          color: #fff;

          .date-card__day,
          .date-card__date,
          .date-card__month {
            color: #fff;
          }
        }
      }
    }

    .date-card__control {
      .bar {
        --wot-progress-height: 20px;
        --wot-progress-bg: #c7d7f1;
        --wot-progress-color: var(--primary);
      }

      .arrow {
        &.disabled {
          .iconfont {
            color: #b1bed5;
          }
        }

        .iconfont {
          font-size: 42px;
          color: var(--primary);
        }
      }
    }
  }

  .time-selector {
    background: #e2ecfc;
    border-radius: 20px;

    .time-selector__title {
      font-size: 32px;
      font-weight: 500;
      color: #4a4a4a;
    }

    .time-selector__desc {
      color: var(--secondary-text-color);
      font-size: 26px;
    }

    .time-selector__content {
      .time-selector__item {
        background: #ffffff;
        border-radius: 10px;
        color: #3d3d3d;
        padding: 26px 0;
        text-align: center;
        font-size: 30px;
        font-weight: 600;
        box-sizing: border-box;
        border: 2px solid rgba(255, 255, 255, 0.5);

        .time-selector__desc {
          font-size: 24px;
          font-weight: 350;
          &.disabled {
            color: #8b8e93;
            text-decoration: line-through;
          }

          &.warning {
            color: #cb8100;
          }

          &.normal {
            color: #1b71df;
          }

          &.danger {
            color: #c83200;
          }
        }

        &.active {
          background: var(--primary);
          color: #fff;
          .time-selector__desc {
            color: #fff;
          }
        }

        &.disabled {
          background: rgba(247, 250, 254, 0.5);
          color: #8b8e93;
        }
      }
    }
  }

  .next-btn {
    --wot-button-medium-height: 89px;
    --wot-button-medium-fs: 36px;

    :deep(.wd-button) {
      font-weight: bold;
    }
  }
}
</style>
